<script setup>
import {computed, defineProps, onMounted, ref, watchEffect} from "vue";
import {GetApp} from "@/api/app.js";
import {ElButton, ElMessage} from "element-plus";
import { useRouter } from "vue-router";
import { userInfoStore} from "@/store/userInfoStore.js";
// import ShareModal from "@/components/ShareModal.vue";
import {AppType} from "@/Constant/App/appType.js";
import {AppScoringStrategy} from "@/Constant/App/appScoringStrategy.js";
import AddAppComponent from "@/components/admin/appAdmin/AddAppComponent.vue";
import UserUpdateAppComponent from "@/components/admin/appAdmin/UserUpdateAppComponent.vue";

const props = defineProps({
  id: {
    type: String,
    default: "",
  },
});

//修改App
const updateAppRef = ref(null);

const openUserUpdateAppDialog = async () => {
  if (updateAppRef.value) {
    await updateAppRef.value.showUserUpdateAppDialog(Number(props.id));
  }
};

onMounted(()=>{
  console.log("detail is running")
})
const router = useRouter();

const data = ref({
  user:null,
});

// 获取登录用户
const loginUserStore = userInfoStore();
const loginUserId = loginUserStore.info.id;
// 是否为本人创建
const isMy = computed(() => {
  console.log("loginUserId: ",loginUserId);
  const userId = data.value.user?.id;
  return loginUserId && loginUserId === userId;
});

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.id) {
    return;
  }
  try {
    const res = await GetApp(props.id);
    console.log("res: ",res);
    if (res.code === 0) {
      data.value = res.data;
    } else {
      ElMessage.error("获取数据失败，" + res.message);
    }
  } catch (error) {
    console.error("Error fetching data:", error);
    ElMessage.error("获取数据时发生错误");
  }
};

/**
 * 监听 searchParams 变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  loadData();
});

// 分享弹窗的引用
const shareModalRef = ref();

// 分享链接
const shareLink = `${window.location.protocol}//${window.location.host}/app/detail/${props.id}`;

// 分享
const doShare = (e) => {
  if (shareModalRef.value) {
    shareModalRef.value.openModal();
  }
  // 阻止冒泡，防止跳转到详情页
  e.stopPropagation();
};
</script>

<template>
  <div id="appDetailPage">
    <el-card>
      <el-row :gutter="16" style="margin-bottom: 16px">
        <el-col :span="18" class="content-wrapper">
          <h2>{{ data.appName }}</h2>
          <p>{{ data.appDesc }}</p>
          <p>应用类型：{{Object.keys(AppType).find(key => AppType[key] === data.appType)}}</p>
          <p>评分策略：{{Object.keys(AppScoringStrategy).find(key => AppScoringStrategy[key] === data.scoringStrategy)}}</p>
          <p>
            <el-space>
              作者：
              <div :style="{ display: 'flex', alignItems: 'center' }">
                <el-avatar
                    :size="24"
                    :src="data.user?.user_pic"
                    :style="{ marginRight: '8px' }"
                />
                <span>{{ data.user?.nickname ?? "无名" }}</span>
              </div>
            </el-space>
          </p>
          <p>
            创建时间：{{ data.createTime }}
          </p>
          <el-space size="medium">
            <el-button type="primary" @click="router.push(`/answer/do/${props.id}/${data.scoringStrategy}`)">开始答题</el-button>
            <el-button @click="doShare">分享应用</el-button>
            <el-button v-if="isMy" @click="router.push(`/add/question/${props.id}`)">设置题目</el-button>
            <el-button v-if="isMy" @click="router.push(`/add/scoring_result/${props.id}/${data.appName}/${data.appType}/${data.scoringStrategy}`)">设置评分</el-button>
            <el-button @click="router.push(`/answer/result/${props.id}`)">作答情况</el-button>
            <el-button v-if="isMy"  @click="openUserUpdateAppDialog">修改应用</el-button>
            <UserUpdateAppComponent ref="updateAppRef" @call-parent="loadData" />
          </el-space>
        </el-col>
        <el-col :span="6">
          <el-image style="width: 100%" :src="data.appIcon" />
        </el-col>
      </el-row>
    </el-card>
    <ShareModal :link="shareLink" title="应用分享" ref="shareModalRef" />
  </div>
</template>

<style scoped>
#appDetailPage {
}

#appDetailPage .content-wrapper > * {
  margin-bottom: 24px;
}
</style>

<style scoped>
#appDetailPage {
}

#appDetailPage .content-wrapper > * {
  margin-bottom: 24px;
}
</style>